#include <stdlib.h>
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <getopt.h>
#include "globle.h"

#define LOG_TAG  "cmd.c  :"

int create_cmd_trans_channel(void)
{
    int ret_val = -1, tmp_fd = -1;
    if (access(NAMED_PIPE_PATH, F_OK) == 0)
    {
        ret_val = remove(NAMED_PIPE_PATH);
        if (ret_val < 0)
        {
            LOGE(LOG_TAG"remove named_pipe faild,errno = %d!\r\n", errno);
            return -errno;
        }
    }
    ret_val = mkfifo(NAMED_PIPE_PATH, 0777);
    if (ret_val < 0)
    {
        LOGE(LOG_TAG"named_pipe initial faild,errno = %d!\r\n", errno);
        return -errno;
    }
    chmod(NAMED_PIPE_PATH, 0766);
    tmp_fd = open(NAMED_PIPE_PATH, O_RDWR);
    if (ret_val < 0)
    {
        LOGE(LOG_TAG"open named_pipe faild,errno = %d!\r\n", errno);
        return -errno;
    }
    return tmp_fd;
}

int cmd_handle(int cmd_channel_fd, xdma_usr_dev *xdma_dev)
{
    int tmp_cmd = -1, ret_val = -1; //需要和algo_if.c中的cmd数据类型对应
    printf("test point 7 cmd_channel_fd = %d \r\n", cmd_channel_fd);
    ret_val = read(cmd_channel_fd, &tmp_cmd, sizeof(tmp_cmd));          //卡主 没读出来东西？
    printf("test point 7+ \r\n");
    if (ret_val < 0)
    {
        LOGE(LOG_TAG"read cmd_channel_fd faild,errno = %d!\r\n", errno);
        return -errno;
    }
    if (tmp_cmd < 0 || tmp_cmd >= CMD_MAX)
    {
        LOGE("illegal cmd:%d\r\n",tmp_cmd);
        return -EINVAL;
    }
    
    switch (tmp_cmd)
    {
        case CMD_START:
            xdma_dev->deliver_data = 1;
            LOG("--------rcv cmd,transport raw data to algo!--------\r\n");
            break;
        case CMD_STOP:
            xdma_dev->deliver_data = 0;
            LOG("--------rcv cmd,stop transporting raw data to algo!--------\r\n");
            break;
        default:
            break;
    }
    return 0;
}
